package rwheel

import (
	"context"
	"log"
	"time"
)

type FuncName struct {
	Key      string        `json:"key"`
	RunTime  int64         `json:"run_time"`
	Interval time.Duration `json:"interval"`
}

type _timerFunc struct {
	key         string
	ctx         *context.Context
	fx          Func
	nextRunTime int64
}

func (t *_timerFunc) Run() {
	defer func() {
		if r := recover(); r != nil {
			log.Println("timeWheel.timerFunc panic:", r)
		}
	}()
	select {
	case <-(*t.ctx).Done():
		return
	default:
		t.fx(t.key, t.ctx)
	}
}

type _tickerFunc struct {
	key         string
	ctx         *context.Context
	fx          Func
	nextRunTime int64
	interval    time.Duration
}

func (t *_tickerFunc) Run(now time.Time) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("timeWheel._tickerFunc panic:", r)
		}
	}()
	select {
	case <-(*t.ctx).Done():
		RemoveTickerFunc(t.key)
		return
	default:
		t.nextRunTime = now.Add(t.interval).UnixMilli()
		t.fx(t.key, t.ctx)
	}
}
